package com.example.statistics.ex

import android.content.Context
import android.util.Log
import com.google.gson.Gson
import com.google.gson.JsonSyntaxException
import java.io.Serializable
import java.util.*

/**
 * 个人偏好设置
 * Created by jhj on 17-7-31.
 */


fun <T : Any> Context.preferenceSave(entity: T?, key: String): Boolean {
    if (entity == null) {
        return false
    }
    val prefFileName = entity.javaClass.name
    val sp = getSharedPreferences(prefFileName, 0)
    val et = sp.edit()
    try {
        val json = Gson().toJson(entity)
        et.putString(key, json)
    } catch (e: Exception) {
        Log.e("", "数据生成gson字符串失败")
    }
    return et.commit()
}

fun <T> Context.preferenceFindAll(clazz: Class<T>): List<T> {
    val prefFileName = clazz.name
    val sp = getSharedPreferences(prefFileName, 0)
    val values = sp.all as Map<String, String>?

    val results = ArrayList<T>()

    if (values == null || values.isEmpty())
        return results

    for (json in values.values) {
        try {
            val bean = Gson().fromJson(json, clazz) as T
            bean?.let { results.add(it) }
        } catch (e: JsonSyntaxException) {
            Log.e("", "解析gson字符串失败")
        }
    }
    return results
}

fun <T> Context.preferenceFind(clazz: Class<T>, key: String): T? {
    val prefFileName = clazz.name
    val sp = getSharedPreferences(prefFileName, 0)
    val json = sp.getString(key, null) ?: return null
    try {
        return Gson().fromJson(json, clazz) as T
    } catch (e: JsonSyntaxException) {
        Log.e("", "解析gson字符串失败")
    }
    return null
}

fun <T : Serializable> Context.preferenceDelete(clazz: Class<T>, key: String) {
    val prefFileName = clazz.name
    val sp = getSharedPreferences(prefFileName, 0)
    if (sp.contains(key)) {
        sp.edit().remove(key).apply()
    }
}

fun <T : Serializable> Context.preferenceDeleteAll(clazz: Class<T>) {
    val prefFileName = clazz.name
    val sp = getSharedPreferences(prefFileName, 0)
    sp.edit().clear().apply()
}
